import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  // 状态
  const isDarkTheme = ref(localStorage.getItem('theme') === 'dark')
  const primaryColor = ref(localStorage.getItem('primaryColor') || '#1890ff')

  // 主题切换
  const toggleTheme = () => {
    isDarkTheme.value = !isDarkTheme.value
    updateTheme()
  }

  // 更新主题色
  const setPrimaryColor = (color) => {
    primaryColor.value = color
    updateTheme()
  }

  // 更新主题
  const updateTheme = () => {
    // 保存到本地存储
    localStorage.setItem('theme', isDarkTheme.value ? 'dark' : 'light')
    localStorage.setItem('primaryColor', primaryColor.value)

    // 更新 CSS 变量
    const root = document.documentElement
    root.style.setProperty('--primary-color', primaryColor.value)
    
    // 切换暗色/亮色主题
    if (isDarkTheme.value) {
      document.body.classList.add('dark-theme')
      root.style.setProperty('--bg-color', '#1f1f1f')
      root.style.setProperty('--text-color', 'rgba(255, 255, 255, 0.85)')
      root.style.setProperty('--text-color-secondary', 'rgba(255, 255, 255, 0.45)')
      root.style.setProperty('--border-color', '#434343')
      root.style.setProperty('--component-bg', '#2f2f2f')
    } else {
      document.body.classList.remove('dark-theme')
      root.style.setProperty('--bg-color', '#f5f7fa')
      root.style.setProperty('--text-color', 'rgba(0, 0, 0, 0.85)')
      root.style.setProperty('--text-color-secondary', 'rgba(0, 0, 0, 0.45)')
      root.style.setProperty('--border-color', '#e8e8e8')
      root.style.setProperty('--component-bg', '#ffffff')
    }
  }

  // 监听主题变化
  watch([isDarkTheme, primaryColor], () => {
    updateTheme()
  }, { immediate: true })

  return {
    isDarkTheme,
    primaryColor,
    toggleTheme,
    setPrimaryColor
  }
}) 